/*
 * @Description: 添加组织面板
 * @Author: Rfan
 * @Date: 2022-04-08 09:07:14
 * @LastEditTime: 2022-05-25 08:57:50
 */

import { useEffect, useState } from 'react';
import classNames from 'classnames/bind';
import type { Key, SetStateAction } from 'react';
import { fetchDepartmentListByUnitId } from '@/api/department';
import { useAddUserDialogContext } from '../contexts/AddUserDialogContext';
import { useManageRuleContext } from '../../../../contexts/ManageRuleContext';
import TreeTransfer from '@/components/TreeTransfer';

import styles from '../styles/panes.module.scss';

const cx = classNames.bind(styles);

const GroupPane = () => {
  const { selectDepartments, setSelectDepartments } = useAddUserDialogContext();
  const { userList } = useManageRuleContext();
  const [list, setList] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]);

  useEffect(() => {
    fetchDepartmentListByUnitId().then((res) => {
      const { data } = res;
      const ids = userList.map((item: any) => item.departmentId);
      // setList(delItemByIdArray(ids, data));
      setList(
        data.map((item: any) => ({
          ...item,
          disSelect: ids.includes(item.id)
        }))
      );
    });
  }, []);

  const onChange = (nextTargetKeys: SetStateAction<Key[]>, direction: any, moveKeys: any) => {
    setSelectDepartments(nextTargetKeys);
  };

  const onSelectChange = (sourceSelectedKeys: any, targetSelectedKeys: any) => {
    setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
  };

  return (
    <div className={cx('group-pane')}>
      <TreeTransfer
        dataSource={list}
        targetKeys={selectDepartments}
        selectedKeys={selectedKeys}
        rowKey={(item: any) => item.id}
        titles={['组织结构', '已选组织']}
        listStyle={{ height: 300, width: 200 }}
        render={(item: any) => item.deptName}
        fieldNames={{
          title: 'deptName',
          key: 'id'
        }}
        onChange={onChange}
        onSelectChange={onSelectChange}
      />
    </div>
  );
};

export default GroupPane;
